package com.cqyc.shop.comm;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class JdbcUtils {
	private static String username="";
	private static String url="";
	private static String  password="";
	private static Logger logger = LoggerFactory.getLogger(JdbcUtils.class);
	static {
		try {
			Properties prop = new Properties();
			InputStream inputStream=JdbcUtils.class.getResourceAsStream("/jdbc.properties");
			prop.load(inputStream);//以上3步操作是
			username = prop.getProperty("jdbc.username");
			url=prop.getProperty("jdbc.url");
			password = prop.getProperty("jdbc.password");
			Class.forName(prop.getProperty("jdbc.driver"));
			logger.debug("初始化数据库成功");
		} catch (ClassNotFoundException | IOException e) {
			logger.error("初始化异常{}",e.getMessage()); 
		}
	}
	
	public static Connection getConnerction() {
		try {
			return DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			logger.error("连接数据异常{}",e.getMessage());
			 return null;
		}
		
	}
	
	public static void  close(Connection conn,PreparedStatement ps,ResultSet rs) {
		try {
			if(rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			logger.error("关闭结果集异常：{}",e.getMessage());
		}finally {
			try {
				if(ps != null) {
					ps.close();
				}
				
			} catch (Exception e2) {
				logger.error("关闭Statement异常：{}",e2.getMessage());
			}finally {
				try {
					if(conn != null) {
						conn.close();
					}
				} catch (Exception e3) {
					logger.error("关闭连接异常：{}",e3.getMessage());
				}
				
			}
		}
	}
	
}
